module.exports = class {
    constructor() {
        this.sysConfig = require("../../config");

        this.key = "iframe:systemConfig:all";
    }

    static init() {
        return new this();
    }

    /**
     * 从数据库中获取
     */
    async getIframeConfigByDB() {
        return await global.DataBase.iframe_config.Access.findAll({
            raw: true
        });
    };

    /**
     * 同步
     */
    async Sync() {
        let iframeConfig = await this.getIframeConfigByDB();
        let ret = {};
        for (let item of iframeConfig) {
            ret[item.ConfigKey] = item.ConfigValue;
        }
        if (!global.Config.isShareMemory) {
            global.SystemConfig = ret;
        } else {
            let redisClient = global.Redis.getClient();
            let pipeline = redisClient.pipeline();
            for (let key in ret) {
                if (key) {
                    pipeline.set(this.key + ":" + key, ret[key]);
                }

            }
            await pipeline.exec();
        }
        log.info('加载系统配置成功');
        return true;
    };

    /**
     * 获取键的值
     * @param {*键名} KeyName
     */
    async Get(KeyName) {
        if (!global.Config.isShareMemory) {
            return global.SystemConfig[KeyName];
        } else {
            let redisClient = global.Redis.getClient();
            return await redisClient.get(KeyName);
        }
    };


    async Set(KeyName, Value) {
        var item = {
            ConfigKey: KeyName,
            ConfigValue: Value
        };
        await global.DataBase.iframe_config.Access.Access.upsert(item);
        await this.Sync();
    }

    async Del(KeyName) {
        if (!global.Config.isShareMemory) {
            delete global.SystemConfig[KeyName];
        } else {
            let redisClient = global.Redis.getClient();
            await redisClient.del(KeyName);
        }
    }
}